package com.xxlie.auth.repository;

import com.xxlie.auth.domain.Menu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * 菜单DAO接口
 *
 * @author xxlie.com
 * @version 2013-05-15
 */
public interface MenuRepository extends JpaRepository<Menu, Long>, JpaSpecificationExecutor<Menu> {

    @Modifying
    @Query("update Menu set delFlag='" + Menu.DEL_FLAG_DELETE + "' where id = ?1 or parentIds like ?2")
    int deleteById(Long id, String likeParentIds);

    List<Menu> findByParentIdsLike(String parentIds);

    @Query("from Menu where delFlag='" + Menu.DEL_FLAG_NORMAL + "' order by sort")
    List<Menu> findAllList();

    @Query("from Menu where delFlag='" + Menu.DEL_FLAG_NORMAL + "' and show='" + Menu.SHOW + "' order by sort")
    List<Menu> findAllShowList();

    @Query("from Menu where delFlag='" + Menu.DEL_FLAG_NORMAL + "' and show='" + Menu.SHOW + "' and parent.id='1' order by sort")
    List<Menu> findRootShowList();

    @Query("from Menu where delFlag='" + Menu.DEL_FLAG_NORMAL + "' and show='" + Menu.SHOW
            + "' and shortcut='" + Menu.SHORTCUT_YES + "' order by sort")
    List<Menu> findShortcutList();

    @Query("select distinct m from Menu m, Role r, User u where m in elements (r.menuList) and r=u.role" +
            " and m.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and r.delFlag='" + Menu.DEL_FLAG_NORMAL +
            "' and u.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and u.id=?1" + // or (m.user.id=?1  and m.delFlag='" + Menu.DEL_FLAG_NORMAL + "')" +
            " order by m.sort")
    List<Menu> findByUserId(Long userId);

    @Query("select distinct m from Menu m, Role r, User u where m in elements (r.menuList) and r=u.role" +
            " and m.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and r.delFlag='" + Menu.DEL_FLAG_NORMAL +
            "' and u.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and u.id=?1 and m.show='" + Menu.SHOW +
            "' order by m.sort")
    List<Menu> findShowByUserId(Long userId);

    @Query("select distinct m from Menu m, Role r, User u where m in elements (r.menuList) and r=u.role" +
            " and m.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and r.delFlag='" + Menu.DEL_FLAG_NORMAL +
            "' and u.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and u.id=?1 and m.show='" + Menu.SHOW +
            "' and m.parent.id='1' order by m.sort")
    List<Menu> findRootShowByUserId(Long userId);

    @Query("select distinct m from Menu m, Role r, User u where m in elements (r.menuList) and r=u.role" +
            " and m.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and r.delFlag='" + Menu.DEL_FLAG_NORMAL +
            "' and u.delFlag='" + Menu.DEL_FLAG_NORMAL + "' and u.id=?1 and m.show='" + Menu.SHOW +
            "' order by m.sort")
    List<Menu> findShortcutByUserId(Long userId);
}